<template>
  <div class="edit" ﻿@tap="focus=false">
    <div class="edit-title">
        <input type="text" placeholder="请输入标题" @input="titleInput" maxlength="50" placeholder-style="color:#EF5A56;">
    </div>
    <div class="edit-textarea" ﻿@tap.stop="focus=true">
      <textarea placeholder="我的快乐源泉..." @input="contentInput" auto-height :focus="focus" placeholder-style="color:#B8B8B8;"/>
    </div>
    <div class="imgContent cf">
      <div class="imgDiv fl" v-for="(item,index) in tempFilePathsArr" :key="index" ﻿@tap="previewImage($event,item)">
          <img :src=item alt="" mode="aspectFill">
          <span class="deleteImg" ﻿@tap.stop="deleteImg(index)"><i class="icon iconfont iconshanchu1" style="color: #F05955;"></i></span>
      </div>
      <div class="chooseImg fl" v-if="tempFilePathsArr.length < 9">
        <i ﻿@tap.stop="chooseImg" class="iconfont icontianjiatupian" style="font-size: 200rpx;color: #DADADA;display: inline-block;"></i>
      </div>
      <div style="clear: both;"></div>
    </div>
    <div class="edit-footer">
      <p class="issueBtn" ﻿@tap="issueBtn">发布</p>
    </div>
  </div>
</template>

<script>
  import { getToken } from "@/tool/qiniu";
    export default {
        name: "edit",
      data(){
          return{
            id: "",
            title: "",
            isTitle: false,
            content: "",
            focus: false,
            tempFilePathsArr: [],
            sign: {},
            postData:{
              token: ""
            },
            imgList:[],
            isClick:true
          }
      },
      onUnload () {
        // 页面卸载时 清空页面数据
        Object.assign(this.$data, this.$options.data())
      },
        methods:{
          titleInput(e){
            if(e.target.cursor === 50){
              uni.showToast({
                title: "输入框字数达到上限！",
                icon: 'none',
                duration: 2000
              })
            }
            this.title = e.mp.detail.value;
            var patt=/[\ud800-\udbff][\udc00-\udfff]/g;
            if(patt.test(e.mp.detail.value)){
              this.isTitle = false;
            }
            else {
              this.isTitle = true;
            }

          },
          contentInput(e){
            if(e.target.cursor === 140){
              uni.showToast({
                title: "输入框字数达到上限！",
                icon: 'none',
                duration: 2000
              })
            }
            this.content = e.mp.detail.value;
          },
        chooseImg: function () {
          let that = this;
          let imgArr = [];
          let count = 0;
          uni.chooseImage({
            count: 9 - that.tempFilePathsArr.length, // 默认最多一次选择9张图
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              // 支持多图上传
              setTimeout(function () {
              uni.showLoading({
                title: '请稍后...',
                mask: true
              });
              }, 500);
              imgArr = res.tempFilePaths;
              for (let i = 0; i < res.tempFilePaths.length; i++) {
                // 验证格式
                if (!/.(jpg|jpeg|png)$/i.test(res.tempFilePaths[i])) {
                  setTimeout(function () {
                    uni.showToast({
                      title: '图片格式有误',
                      icon: 'none',
                      duration: 2000
                    })
                  }, 500)
                  return
                }
                if (res.tempFiles[i].size > 1024*1024) {
                  setTimeout(function () {
                    uni.showToast({
                      title: '图片应小于1M',
                      icon: 'none',
                      duration: 2000
                    })
                  }, 500)
                  return
                }
                uni.uploadFile({
                  url: that.$api.checkImg,
                  filePath: imgArr[i],
                  name: "file",
                  header:{
                    Cookie : "frontend="+ uni.getStorageSync('sessionId'),
                    token: uni.getStorageSync('token')
                  },
                  success(res){
                    count++;
                    let result = JSON.parse(res.data);
                    if(result.data.status === 200){
                      that.tempFilePathsArr.push(imgArr[i]);
                    } else {
                      setTimeout(function () {
                        uni.showToast({
                          title: result.data.msg,
                          icon: 'none',
                          duration: 2000
                        })
                      }, 500);
                    }
                    if(count === imgArr.length ){
                      setTimeout(function() {
                        uni.hideLoading()
                      }, 500);
                    }
                  },
                  fail: function (error) {
                    count++;
                    if(count === imgArr.length ){
                      setTimeout(function() {
                        uni.hideLoading()
                      }, 500);
                    }
                    setTimeout(function () {
                      uni.showToast({
                        title: '上传图片失败',
                        icon: 'none',
                        duration: 2000
                      })
                    }, 500);
                  }
                })

              }
            }
          })
        },
        deleteImg (index) {
          let that = this;
          uni.showModal({
            title: '提示',
            content: '确定删除这张照片吗？',
            confirmColor: '#c6ae6c',
            success (res) {
              if (res.confirm) {
                that.tempFilePathsArr.splice(index, 1);
                that.imgList = [];
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        },
        // 小程序图片预览
        previewImage: function (e, item) {
          uni.previewImage({
            current: item, // 当前显示图片的http链接
            urls: this.tempFilePathsArr // 需要预览的图片http链接列表
          })
        },
        issueBtn(){
          if(this.isClick) {
            this.isClick = false;
            setTimeout(() => {
              this.isClick = true;
            }, 3000);//一秒内不能重复点击
            if(this.title === ""){
              uni.showToast({
                title: "请输入标题！",
                icon: 'none',
                duration: 2000
              })
            }
            else if(!this.isTitle){
              uni.showToast({
                title: "标题格式不正确，请重新输入！",
                icon: 'none',
                duration: 2000
              })
            }
            else if(this.content !== "" && this.tempFilePathsArr.length > 0){
              uni.showLoading({
                title: '发布中...',
                mask: true
              });
              this.uploadImg();
            }
            else if(this.content !== "" || this.tempFilePathsArr.length > 0){
              // 显示消息提示框
              uni.showLoading({
                title: '发布中...',
                mask: true
              });
              if(this.content !== ""){
                this.imgList = [];
                this.addPosts();
              }
              else {
                this.uploadImg();
              }
            }
            else {
              uni.showToast({
                title: "请输入内容！",
                icon: 'none',
                duration: 2000
              })
            }
          }

        },
          uploadImg(){
            let that = this;
            this.imgList = [];
            let count = 0;
            for(let i = 0 ; i < this.tempFilePathsArr.length ; i++){
              uni.uploadFile({
                url: that.$api.postsImgUpload,
                filePath:that.tempFilePathsArr[i],
                name: "file",
                header:{
                  Cookie : "frontend="+ uni.getStorageSync('sessionId'),
                  token: uni.getStorageSync('token')
                },
                success(res){
                  let result = JSON.parse(res.data);
                  if(result.data.status === 200){
                    that.imgList.push(result.data.data.img_url);
                    count ++;
                    if(count === that.tempFilePathsArr.length){
                        that.imgList = that.imgList.join(",");
                        that.addPosts();
                    }
                  } else {
                    setTimeout(function() {
                      uni.hideLoading()
                    }, 500);
                    setTimeout(function () {
                      uni.showToast({
                        title: result.data.msg,
                        icon: 'none',
                        duration: 2000
                      })
                    }, 500);
                  }
                },
                fail: function (error) {
                  setTimeout(function() {
                    uni.hideLoading()
                  }, 400);
                  setTimeout(function () {
                    uni.showToast({
                      title: '上传图片失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }, 500);
                }
              })
            }
          },
          addPosts(){
            if(this.imgList.length === 0){
              this.imgList = "";
            }
            let that = this;
            this.$ajax
              .post(this.$api.addPosts,{
                movie_id:this.id,
                title:this.title,
                describe:this.content,
                img:this.imgList
              })
              .then(() => {
                uni.hideLoading();
                uni.showToast({
                  title: "发布成功待审核！",
                  icon: 'success',
                  duration: 2000
                });
                setTimeout(function() {
					uni.navigateBack({
						delta: 1
					})
                }, 1800)
              })
              .catch(err => {
                uni.showToast({
                  title: err,
                  icon: 'none',
                  duration: 2000
                })
              });
          }
      },
      onLoad(res){
          this.id = res.id;
        this.title = "";
        this.isTitle = false;
        this.content = "";
        this.focus = false;
        this.tempFilePathsArr = [];
        this.sign = {};
        this.imgList = []
      },
    }
</script>

<style scoped>
.edit{
  padding: 40rpx 30rpx 86rpx;
}
  .edit-textarea{
    height: 350rpx;
  }

.imgContent{
  width: 630rpx;
  margin: 0 auto;
}
.imgDiv{
  width:200rpx;
  height:200rpx;
  margin: 10rpx 10rpx 20rpx 0;
  position: relative;
  float: left;
}

.imgDiv img{
  width:200rpx;
  height: 200rpx;
}
.deleteImg{
  position: absolute;
  right: -8rpx;
  top: -20rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #fff;
  display: inline-block;
  border-radius: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.deleteImg .iconfont {
  font-size: 32 rpx;
  color: #C6AE6C;
}

  .edit-footer{
    border-top: 1rpx solid #EEEEEE;
    border-bottom: 1rpx solid #EEEEEE;
    padding: 16rpx 0;
    margin-top: 50rpx;
    display: flex;
    justify-content: flex-end;
    background-color: #ffffff;
  }
  .issueBtn{
    width: 120rpx;
    height: 60rpx;
    border-radius: 6rpx;
    background-color: #EF5A56;
    line-height: 60rpx;
    font-size: 26rpx;
    color: #ffffff;
    text-align: center;
  }
.edit-title{
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #EEEEEE;
}
  .edit-title>input{
    color: #EF5A56;
    font-size: 30rpx;
  }
  .edit-textarea{
    padding-top: 22rpx;
    font-size: 28rpx;
  }
  textarea{
    width: 100%;
  }
</style>
